//安装 npm i express
//导入 express
const express = require('express');

//创建服务对象
const app = express();
const moment = require('moment');
const fs = require('fs');
//定义黑名单 IP
let heimingdan = [
  '::ffff:192.168.20.21',
  '::ffff:192.168.20.40',
  '::ffff:192.168.20.81',
  '::ffff:192.168.20.76',
  '::ffff:192.168.20.23',
];

//声明一个中间件函数
let checkBlackIPList = (req, res, next) => {
  //判断
  if(heimingdan.includes(req.ip)){
    // return res.status(403).send('你想弄啥啦~~');
    return res.send(`
      <h1>弄啥来~~</h1>
      <script>
        for(let i=0;i<1000;i++){
          console.log(i);
        }
      </script>
    `)
  }
  //执行后续回调
  next();
}

//声明一个中间件函数
let recordMiddleware = (req, res, next) => {
  //获取当前的时间   [2023-02-02 12:12:12]  /home  IP
  let timeStr = moment().format('YYYY-MM-DD HH:mm:ss');
  fs.appendFileSync('./access.log', `[${timeStr}]  ${req.url}  ${req.ip}\r\n`);
  res.setHeader('content-type','text/html;charset=utf-8');
  //调用 next 函数
  next();
};
//使用中间件
app.use(checkBlackIPList);
//使用中间件函数
app.use(recordMiddleware);

//创建路由规则
app.get('/', (req, res) => {
  res.end('欢迎来到红浪漫~~');
});

app.get('/hello', (req, res) => {
  res.end('Hello Express');
});

app.get('/admin', (req, res) => {
  res.send('后台首页');
});

//监听端口 启动服务
app.listen(80, () => {
  console.log('服务已经启动....');
})